﻿<html>
<head>
<script src="new_GetBingMapKey"></script>
<script src="ClientGlobalContext.js.aspx" ></script>
<script language="javascript" type="text/javascript">
		var adminDistrict;
		var adminDistrictField;
		var locality;
		var localityField;
		var postalCode;
		var postalCodeField;
		var addressLine;
		var addressLineField;
		var countryRegion;
		var countryRegionField;
		var latField;
		var longField;
	function GetLocation(jsonObj)
	{
			if(jsonObj.resourceSets && jsonObj.resourceSets[0].estimatedTotal > 0)
				{
					var lat = jsonObj.resourceSets[0].resources[0].point.coordinates[0];
					var lng = jsonObj.resourceSets[0].resources[0].point.coordinates[1];
					parent.Xrm.Page.ui.controls.get(latField).getAttribute().setValue(lat);
					parent.Xrm.Page.ui.controls.get(longField).getAttribute().setValue(lng);
					RenderMap();
				}
				else
				{
					alert("Unable to locate the address. Please give more details or use the below map.");
				}
	}
    function FillLatLong() {
		
		
		var url;
        var xmlhttp = null;	
		//Read address fields
        ReadAddressFields();
		
		//Generate url to call bing REST service.
		GenerateBingMapUrl();
		
		var scriptTag = document.createElement("script");
		scriptTag.setAttribute('src', url);
		scriptTag.setAttribute('type', 'text/javascript');
		document.body.appendChild(scriptTag);
		
		function ReadAddressFields()
		{
			GetFieldNames();
			var controls = parent.Xrm.Page.ui.controls;
			//ToDo: See if check is required to see if getAttribute returns null.
			//State
			if(adminDistrictField)
			{
				adminDistrict = controls.get(adminDistrictField).getAttribute().getValue();
			}
			
			//City
			if(localityField)
			{
				locality = controls.get(localityField).getAttribute().getValue();
			}
			
			//Postal Code
			if(postalCodeField)
			{
				postalCode = controls.get(postalCodeField).getAttribute().getValue();
			}
			
			//addressline
			if(addressLineField)
			{
				addressLine = controls.get(addressLineField).getAttribute().getValue();
				//addressLine = addressLine + " " + controls.get("address1_line1").getAttribute().getValue();
			}
			
			//Country
			if(countryRegionField)
			{
				countryRegion = controls.get(countryRegionField).getAttribute().getValue();
			}
		}
		
		function GenerateBingMapUrl()
		{
			if(location.protocol == "http:")
			{
				url = "http://dev.virtualearth.net/REST/v1/Locations?";
			}
			else
			{
				url = "https://dev.virtualearth.net/REST/v1/Locations?";
			}
			var reg = /[^a-zA-Z0-9]+/g;
			if(adminDistrict)
			{
				adminDistrict = adminDistrict.replace(reg,' ');
				url += "adminDistrict=" + adminDistrict +"&";
			}
			if(locality)
			{
				locality = locality.replace(reg,' ');
				url += "locality="+ locality + "&";
			}
			if(postalCode)
			{
				postalCode = postalCode.replace(reg,' ');
				url += "postalCode=" +postalCode + "&";
			}
			if(addressLine)
			{
				addressLine = addressLine.replace(reg,' ');
				url += "addressLine= "+ addressLine + "&";
			}
			var bingKey = GetBingMapKey();
			url += "output=json&jsonp=GetLocation&key=" + bingKey;
		}
	
    }
	function GetFieldNames()
		{
			if( adminDistrictField &&
				localityField &&
				postalCodeField &&
				addressLineField &&
				countryRegionField)
				{
					return;
				}
			
			var entityName = parent.Xrm.Page.data.entity.getEntityName();

			if (window.XMLHttpRequest) {
				xHttp = new XMLHttpRequest();
			}
			else {
				xHttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
			xHttp.open("GET", "new_entityAddressFields.xml", false);
			xHttp.send();
			var xmlDoc = xHttp.responseXML;
			
			var entities = xmlDoc.getElementsByTagName('entity');
			for(var i=0; i<entities.length; i++)
			{
				if(entityName == entities[i].getAttribute("name"))
				{
					if(entities[i].getElementsByTagName('state').length > 0)
					{
						adminDistrictField = entities[i].getElementsByTagName('state')[0].getAttribute('name');
					}
					if(entities[i].getElementsByTagName('city').length > 0)
					{
						localityField = entities[i].getElementsByTagName('city')[0].getAttribute('name');
					}
					if(entities[i].getElementsByTagName('postalcode').length > 0)
					{
						postalCodeField = entities[i].getElementsByTagName('postalcode')[0].getAttribute('name');
					}
					if(entities[i].getElementsByTagName('street').length > 0)
					{
						addressLineField = entities[i].getElementsByTagName('street')[0].getAttribute('name');
					}
					if(entities[i].getElementsByTagName('country').length > 0)
					{
						countryRegionField = entities[i].getElementsByTagName('country')[0].getAttribute('name');
					}
					if(entities[i].getElementsByTagName('latitude').length > 0)
					{
						latField = entities[i].getElementsByTagName('latitude')[0].getAttribute('name');
					}
					if(entities[i].getElementsByTagName('longitude').length > 0)
					{
						longField = entities[i].getElementsByTagName('longitude')[0].getAttribute('name');
					}
				}
				
			}
		}
</script>
<script type="text/javascript" src="https://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.2"></script>
<script type="text/javascript">
	var map = null;
	var pos = null;
	function RenderMap()
	{
		var controls = parent.Xrm.Page.ui.controls;
		GetFieldNames();
		if( controls.get(latField).getAttribute().getValue() != null &&
			controls.get(longField).getAttribute().getValue() != null)
			{
				GetMap(controls.get(latField).getAttribute().getValue(), controls.get(longField).getAttribute().getValue());
			}
	
		function MouseHandler(e)
		{
			if (e.eventName == "onclick")
			{
				if (e.rightMouseButton)
				{
					var ll = map.PixelToLatLong(new VEPixel(e.mapX,e.mapY));
					parent.Xrm.Page.ui.controls.get(latField).getAttribute().setValue(ll.Latitude);
					parent.Xrm.Page.ui.controls.get(longField).getAttribute().setValue(ll.Longitude);
					SetPushPin(ll.Latitude, ll.Longitude);
				}
			}
		}
		function SetPushPin(lat, lng)
		{
			var latLong = new VELatLong(lat, lng);
			if(pos != null)
			{
				map.DeleteShape(pos);
				pos = null;
			}
			pos = new VEShape(VEShapeType.Pushpin, latLong);
			pos.SetTitle('Record location');
			map.AddShape(pos);
		}
		function GetMap(lat, lng)
		{
			if(map == null)
			{
				map = new VEMap('myMap');
			}
			map.LoadMap(new VELatLong(lat, lng), 12, 'r', false);
			map.AttachEvent("onclick", MouseHandler);
			SetPushPin(lat, lng);
		}
	}
</script>

</head>
<body onload="RenderMap()">
<button type="button" onclick="FillLatLong()">FillLatLong</button>
<div id='myMap' style="position:relative; width:100%; height:100%;"></div>
</body>
</html>